<?php
// 获取参数
$page = $_GET["page"];
$cur = $_GET["cur"];

// 预连接数据库
$conn = mysqli_connect("localhost", "root", "Passw0rdTypecho","bestscu_wenake_t");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// echo "连接成功";

// 先查有多少条评论
$sqlAskTotal = "SELECT id FROM comments WHERE page='".$page."'";
$ret = mysqli_query($conn,$sqlAskTotal);
$cmt_num = $ret->num_rows;

if($cur == NULL or $cur<=0){
    // 只是查询评论数目，返回结果并即时去世
    echo '{"total": '.$cmt_num.'}';
    mysqli_close($conn);
    die();
}

// if($cur * 3 > $cmt_num){
//     echo "Error: No more comments";
// }
// 分页式查询
$sql = "SELECT username, content, time FROM comments WHERE page='".$page."' ORDER BY time DESC LIMIT ".(3 * $cur - 3).",3";

$arr = array();

$cnt=0;

# ret是查询返回的结果对象
if($ret = mysqli_query($conn,$sql))
{
    while($obj = mysqli_fetch_object($ret))
    {
        # 这里从ret中一次次取出每一个username content对，然后加入arr中
        array_push($arr,array("username" => $obj->username, "content" => $obj->content ));
        $cnt += 1;
    }
    mysqli_free_result($ret);
    # 释放对象
}
mysqli_close($conn);
// 关闭连接
$response = array("total" => $cnt);
array_push($response, $arr);
echo json_encode($response);


?>